package cn.com.miao.lynx.service.system.service.impl;

import cn.com.miao.lynx.common.base.repository.BaseRepository;
import cn.com.miao.lynx.common.dict.api.DictParam;
import cn.com.miao.lynx.common.dict.api.DictResult;
import cn.com.miao.lynx.common.dict.api.RemoteDictService;
import cn.com.miao.lynx.service.system.entity.QSysDict;
import cn.com.miao.lynx.service.system.entity.QSysDictItem;
import cn.com.miao.lynx.service.system.entity.SysDictItem;
import cn.com.miao.lynx.service.system.repository.SysDictItemRepository;
import cn.com.miao.lynx.service.system.service.SysDictItemService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * SysDictItemServiceImpl
 *
 * @title: SysDictItemServiceImpl
 * @description:
 * @author: dengmiao
 * @create: 2019-12-30 10:25
 **/
@Slf4j
@Data
@AllArgsConstructor
@Service
public class SysDictItemServiceImpl implements SysDictItemService, RemoteDictService {

    private final SysDictItemRepository sysDictItemRepository;

    @Override
    public BaseRepository<SysDictItem, Long> getRepository() {
        return this.getSysDictItemRepository();
    }

    @Override
    public DictResult loadDictByCode(DictParam dictParam) {
        SysDictItem dictItemByDictCodeAndValue = findDictItemByDictCodeAndValue(dictParam.getCode(), dictParam.getValue());
        return DictResult.builder()
                .dictText(Optional.ofNullable(dictItemByDictCodeAndValue).get().getItemText())
                .build();
    }

    @Override
    public SysDictItem findDictItemByDictCodeAndValue(String code, String value) {
        QSysDict _Q_SysDict = QSysDict.sysDict;
        QSysDictItem _Q_SysDictItem = QSysDictItem.sysDictItem;
        return jpaQueryFactory().select(_Q_SysDictItem)
                .from(_Q_SysDict, _Q_SysDictItem)
                .where(
                        _Q_SysDict.id.eq(_Q_SysDictItem.dictId),
                        _Q_SysDict.dictCode.eq(code),
                        _Q_SysDictItem.itemValue.eq(value)
                )
                // 字典code和itemValue唯一确定一个字典值
                .fetchOne();
    }
}
